package com.fit.pages;

import java.util.List;

import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.UserAccess;
import com.fit.dao.vehicle.VehicleDAO;
import com.fit.entities.Vehicle;
@UserAccess
@AdminAccess
public class Index {
	@Property
	private List<Vehicle> vehicles;

	@Property
	private Vehicle vehicle;

	@Inject
	private VehicleDAO vehicleDAO;

	@Persist
	@Property
	private String error;

	@Persist
	@Property
	private String confirmation;

	void onActivate() {
		vehicles = vehicleDAO.findAll();
	}

	@OnEvent(component = "deleteLink")
	Object onDeleteLink(String chassisNumber) {
		error = "";
		confirmation = "";
		Vehicle v = vehicleDAO.findByChassisNumber(chassisNumber);
		if (vehicleDAO.checkRegistrations(v)) {
			error = "You can't delete vehicle associated with some registrations!";
			return null;
		}
		try {
			vehicleDAO.deleteByChassisNumber(chassisNumber);
			confirmation = "Vehicle successfully deleted.";
			return null;
		} catch (Exception e) {
			error = "Error deleting vehicle. ";
			return null;
		}
	}

	@OnEvent(component = "ResetConfLink")
	Object onResetConfLink() {
		confirmation = "";
		return null;
	}

	@OnEvent(component = "ResetErrorLink")
	Object onResetErrorLink() {
		error = "";
		return null;
	}

	public boolean isErrorNotNull() {
		if (error == null || error == "") {
			return false;
		}
		return true;
	}

	public boolean isConfirmationNotNull() {
		if (confirmation == null || confirmation == "") {
			return false;
		}
		return true;
	}
}
